import pandas as pd
import jiagu
from base_handle import BaseHandle  # 引入工具类

baseHandle = BaseHandle()  # 实例化

'''
3.1 基于 jiagu 的情感分析
'''

def jiagu_cal(url):
    '''计算每条评论的情感值'''
    df = pd.read_excel(url, sheet_name='Sheet1')
    # print(df)
    # 定义函数，批量处理所有的评论信息
    def get_sentiment_cn(text):
        return jiagu.sentiment(text)[1]  # jiagu的后边带positive或negative

    # 根据df里的“comments”列，将读取文本后的情感分析结果添加到新的一列，命名为“sentiment”
    df["sentiment"] = df['评论'].apply(get_sentiment_cn)
    # print(df)
    # 储存为表格。
    df.to_excel('Jiagu情感分析原始结果_京东.xlsx')


def match_words_jiagu():
    '''匹配关键词和情感分析结果'''
    words = baseHandle.logistics_list
    items = []
    for word in words:
        row = handle_senti_result(word, "评论", "情感值")
        row.insert(0, word)
        items.append(row)
    dt = pd.DataFrame(items, columns=['关键词', '评论数量', '好评率', '情感值方差', '情感均值', '情感中值'])
    dt.to_excel("jiagu情感分析匹配结果_京东.xlsx")


def handle_senti_result(word, col1, col2):
    '''子方法—统计每个关键词的情感值大小'''
    df = pd.read_excel('Jiagu情感分析原始结果_京东.xlsx', sheet_name='Sheet1')
    b1 = []
    b2 = []
    for i in range(len(df)):
        comment = df.loc[i, col1]
        if word in comment:  # 判断关键词是否存在于某个字符串(str)中
            a1 = df.loc[i, col1]
            a2 = df.loc[i, col2]
            if not a1 in b1:  # col1:评论,col2:情感值,去掉重复的评论,也可不去掉
                b1.append(a1)
                b2.append(a2)
            else:
                continue
        else:
            continue
    f1 = pd.DataFrame(columns=['评论', '情感值'])
    f1['评论'] = b1
    f1['情感值'] = b2
    # print('分值之和：',f1['情感值'].sum())
    seti = f1['情感值']
    # 一些列数据
    row = [seti.count(), f1[seti >= 0.6]['情感值'].count() / seti.count(),
           seti.var(), seti.mean(), seti.median()]
    return row


if __name__ == "__main__":
    jiagu_cal(baseHandle.get_file_abspath('语料库_京东_5000条评论.xlsx'))

    match_words_jiagu()
